package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.enums.CounponMoneyEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.eunm.ActivityEnums;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.service.DynamicAndTopicService;
import com.ytjj.qmyx.admin.service.DynamicService;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.UserBalanceDto;
import com.ytjj.qmyx.users.model.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description TODO
 *
 * @Version 1.0
 * 
 */

@Service
@Slf4j
@RefreshScope
public class DynamicServiceImpl implements DynamicService {

    @Resource
    private BannersMapper bannersMapper;
    @Resource
    private BannerDao bannerDao;
    @Resource
    private DynamicDao dynamicDao;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private ImgMapper imgMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private BedImgDao bedImgDao;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductDao productDao;

    @Resource
    private SpecialMapper specialMapper;

    @Resource
    private DynamicSpecialMapper dynamicSpecialMapper;

    @Resource
    private DynamicCommentDao dynamicCommentDao;

    @Resource
    private DynamicCommentMapper dynamicCommentMapper;

    @Resource
    private ProductMatchingDao productMatchingDao;

    @Resource
    private DynamicMatchingMapper dynamicMatchingMapper;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private DynamicSpecialDao dynamicSpecialDao;

    @Resource
    private EvaluationFlowMapper evaluationFlowMapper;
    @Resource
    private UserDao userDao;
    @Resource
    private OrdersPayMapper ordersPayMapper;
    @Autowired
    private UsersClient usersClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${brokerageRatio:1.6}")
    private String brokerageRatio;
    @Value("${dynamicSendMsgFlag:true}")
    private String dynamicSendMsgFlag;

    @Autowired
    private DynamicAndTopicService dynamicAndTopicService;

    @Autowired
    private DynamicAndTopicDao dynamicAndTopicDao;

    @Autowired
    private DynamicCommentReplyMapper dynamicCommentReplyMapper;

    @Autowired
    private DynamicCommentReplyDao dynamicCommentReplyDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAdImg(AdRequest adRequest) {
        Banners banners = new Banners()
                .setType(adRequest.getType())
                .setProductId(adRequest.getProductId())
                .setSkipType(adRequest.getSkipType())
                .setImgUrl(adRequest.getImgUrl())
                .setStatus(adRequest.getStatus())
                .setSort(adRequest.getSort())
                .setBackgroundColor(adRequest.getBackgroundColor())
                .setRemarks(adRequest.getRemarks())
                .setTitle(adRequest.getTitle())
                .setAPath(adRequest.getAPath())
                .setAppid(adRequest.getAppid())
                .setCreateTime(new Date())
                .setUpdateTime(new Date());
        bannersMapper.insertSelective(banners);
    }

    @Override
    public CommonPage<Banners> getAdImgs(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Banners> allAdImgs = bannerDao.getAllAdImgs();
        return CommonPage.restPage(allAdImgs);
    }

    @Override
    public Banners positionImg(Integer id) {
        return bannersMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAdImg(AdRequest adRequest) {
        Banners banner = bannersMapper.selectByPrimaryKey(adRequest.getId());
        banner.setType(adRequest.getType())
                .setProductId(adRequest.getProductId())
                .setImgUrl(adRequest.getImgUrl())
                .setStatus(adRequest.getStatus())
                .setSort(adRequest.getSort())
                .setBackgroundColor(adRequest.getBackgroundColor())
                .setRemarks(adRequest.getRemarks())
                .setTitle(adRequest.getTitle())
                .setAPath(adRequest.getAPath())
                .setAppid(adRequest.getAppid())
                .setSkipType(adRequest.getSkipType())
                .setUpdateTime(new Date());
        bannersMapper.updateByPrimaryKeySelective(banner);
    }

    @Override
    public void isShowAdImg(AdRequest adRequest) {
        Banners banners = bannersMapper.selectByPrimaryKey(adRequest.getId());
        if (banners.getStatus().equals(adRequest.getStatus())) {
            return;
        }
        banners.setStatus(adRequest.getStatus());
        bannersMapper.updateByPrimaryKeySelective(banners);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBedImg(BedImgRequest bedImgRequest) {
        Img img = new Img();
        img.setType(bedImgRequest.getType());
        img.setNo(bedImgRequest.getNo());
        img.setNoDesc(bedImgRequest.getNoDesc());
        img.setImg(bedImgRequest.getImg());
        img.setContent(bedImgRequest.getContent());
        img.setCreateTime(new Date());
        img.setUpdateTime(new Date());
        imgMapper.insert(img);
    }

    @Override
    public Img acquireBedImg(Integer id) {
        return imgMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editBedImg(BedImgRequest bedImgRequest) {
        Img img = imgMapper.selectByPrimaryKey(bedImgRequest.getId());
        img.setType(bedImgRequest.getType());
        img.setNo(bedImgRequest.getNo());
        img.setNoDesc(bedImgRequest.getNoDesc());
        img.setImg(bedImgRequest.getImg());
        img.setContent(bedImgRequest.getContent());
        img.setUpdateTime(new Date());
        imgMapper.updateByPrimaryKeySelective(img);
    }

    @Override
    public CommonPage<Img> getBedImgList(BedImgRequest bedImgRequest) {
        PageHelper.startPage(bedImgRequest.getPageNum(), bedImgRequest.getPageSize());
        List<Img> imgList = Optional.ofNullable(bedImgDao.getBedImgList(bedImgRequest))
                .orElse(new ArrayList<>());
        return CommonPage.restPage(imgList);
    }

    @Override
    public List<Special> querySpecialList() {
        SpecialExample specialExample = new SpecialExample();
        specialExample.createCriteria().andTypeEqualTo("dynamic");
        return specialMapper.selectByExample(specialExample);
    }

    @Override
    public CommonPage<DynamicCommentReponse> getDynamicCommentList(DynamicCommentRequest dynamicCommentRequest) {
        PageHelper.startPage(dynamicCommentRequest.getPageNum(), dynamicCommentRequest.getPageSize());
        List<DynamicCommentReponse> dynamicComments = dynamicCommentDao.selectList(dynamicCommentRequest);
        if (!CollectionUtils.isEmpty(dynamicComments)) {
            for (DynamicCommentReponse dynamicComment : dynamicComments) {
                List<DynamicCommentReponse> children = dynamicCommentDao.getChildrenByPid(dynamicComment.getId());
                dynamicComment.setChildren(children);
            }
        }
        return CommonPage.restPage(dynamicComments);
    }

    @Override
    public List<DynamicCommentReponse> getChildrenByPid(Integer pid) {
        List<DynamicCommentReponse> dynamicComments = dynamicCommentDao.getChildrenByPid(pid);
        if (!CollectionUtils.isEmpty(dynamicComments)) {
            for (DynamicCommentReponse dynamicComment : dynamicComments) {
                Users users = usersMapper.selectByPrimaryKey(dynamicComment.getUserId());
                dynamicComment.setUserName(users.getNickname());
            }
        }
        return dynamicComments;
    }

    @Override
    public int addDynamicComment(DynamicComment dynamicComment) {
        Users users = usersMapper.selectByPrimaryKey(dynamicComment.getUserId());
        if (users == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.USER_NOT_EXIST));
        }
        if (dynamicComment.getPid() == null) {
            dynamicComment.setPid(0);
        }

        dynamicComment.setCreateTime(new Date());
        dynamicComment.setStatus(1);//虚拟评论默认审核通过
        return dynamicCommentMapper.insertSelective(dynamicComment);
    }

    @Override
    public int updateDynamicComment(DynamicComment dynamicComment) {
        return dynamicCommentMapper.updateByPrimaryKeySelective(dynamicComment);
    }

    @Override
    public int deleteDynamicComment(Integer id) {
        return dynamicCommentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateDynamicCommentStatus(Integer id, Integer status, String remark) {
        return dynamicCommentMapper.updateDynamicCommentStatus(id,status,remark);
    }




    @Override
    public CommonPage<Banners> searchByType(AdRequest adRequest) {
        PageHelper.startPage(adRequest.getPageNum(), adRequest.getPageSize());
        List<Banners> bannersList = Optional.ofNullable(bannerDao.searchAdByType(adRequest.getType()))
                .orElse(new ArrayList<>());
        return CommonPage.restPage(bannersList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDynamic(DynamicRequest dynamicRequest) {
        if (null != dynamicRequest.getUserId() && null != dynamicRequest.getProductId()) {
            Integer pushNum = dynamicDao.countUsePushNum(dynamicRequest.getUserId(), dynamicRequest.getProductId());
            if (null != pushNum && pushNum > 0) {
                throw new ApiException("该商品发布的测评正在审核中，请勿重复发布");
            }
        }
        Users users = usersMapper.selectByPrimaryKey(dynamicRequest.getUserId());
        Product product = productMapper.selectByPrimaryKey(dynamicRequest.getProductId());
        OrdersInfo ordersInfo = null;
        if (dynamicRequest.getOrderInfoId() != null) {
            ordersInfo = ordersInfoMapper.selectByPrimaryKey(dynamicRequest.getOrderInfoId());
            Optional.ofNullable(ordersInfo)
                    .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ORDER_NON_EXISTENT)));
        }

        Optional.ofNullable(users)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.USER_NOT_EXIST)));
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));

        Dynamic dynamic = new Dynamic();
        dynamic.setUserId(dynamicRequest.getUserId());
        dynamic.setTitle(dynamicRequest.getTitle());
        dynamic.setContent(dynamicRequest.getContent());
        dynamic.setPraiseNum(dynamicRequest.getPraiseNum());
        dynamic.setActivityType(dynamicRequest.getActivityType());
        dynamic.setCommentNum(dynamicRequest.getCommentNum());
        dynamic.setImg(dynamicRequest.getImg());
        dynamic.setIsReason(dynamicRequest.getIsReason());
        dynamic.setContent(dynamicRequest.getContent());
        dynamic.setIsZombie(dynamicRequest.getIsZombie());
        if (ordersInfo != null) {
            dynamic.setOrderInfoId(ordersInfo.getId());
        }
        dynamic.setProdcutPrice(dynamicRequest.getProdcutPrice());
        dynamic.setShareNum(dynamicRequest.getShareNum());
        dynamic.setVideo(dynamicRequest.getVideo());
        dynamic.setProductId(dynamicRequest.getProductId());
        dynamic.setProductImg(product.getProductImg());
        dynamic.setProdcutPrice(product.getPrice());
        dynamic.setProductName(product.getProductName());
        dynamic.setActivityType(product.getActivityType());
        dynamic.setIsZeroEvaluation(product.getIsZeroProduct());
        dynamic.setProductType(product.getProductType());
        dynamic.setCreateTime(new Date());
        dynamic.setIsZeroEvaluation(dynamicRequest.getIsZeroEvaluation());
        dynamic.setProductType(dynamicRequest.getProductType());
        dynamic.setStatus((byte) 2);
        dynamic.setIsReason((byte) 1);
        dynamic.setDynamicType(dynamicRequest.getDynamicType());
        dynamic.setDynamicText(dynamicRequest.getDynamicText());
        dynamic.setSort(dynamicRequest.getSort());
        dynamic.setPlatformData(dynamicRequest.getPlatformData());
        dynamic.setIsHome(dynamicRequest.getIsHome());
        dynamic.setCategoryId(dynamicRequest.getCategoryId());
        dynamicMapper.insertSelective(dynamic);

        //1.新增测评关联话题表数据
        List<Integer> integers = dynamicRequest.getDynamicTopics().stream().map(e->e.getId()).collect(Collectors.toList());
        dynamicAndTopicService.createDynamicTopicRelations(dynamic.getId(),integers,dynamicRequest.getSortAtTopic());

        //插入数据成功后，返回动态Id
        Integer dynamicId = dynamic.getId();

        //同步商品推荐信息到动态管理-推荐列表中
        ProductMatching productMatching = productMatchingDao.getProductMatching(dynamicRequest.getProductId());
        if (productMatching == null) {
            throw new ApiException("商品推荐信息为空！");
        }
        DynamicMatching dynamicMatching = new DynamicMatching();
        dynamicMatching.setDynamicId(dynamicId);
        dynamicMatching.setSex(productMatching.getSex());
        dynamicMatching.setComsumerPower(productMatching.getComsumerPower());
        dynamicMatching.setAgeStr(productMatching.getAgeStr());
        dynamicMatching.setProvinceJson(productMatching.getProvinceJson());
        dynamicMatching.setLabelJson(productMatching.getLabelJson());
        dynamicMatching.setCreateTime(new Date());
        dynamicMatching.setUpdateTime(null);
        dynamicMatchingMapper.insertSelective(dynamicMatching);

    }

    @Resource
    private EvaluationProductDao evaluationProductDao;

    @Resource
    private MallClient mallClient;

    @Override
    public void videoPass(DynamicRequest dynamicRequest) {
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicRequest.getId());
        if (dynamic.getStatus().equals(dynamicRequest.getStatus())) {
            return;
        }
        // 状态：1为审核通过，0为不显示，2审核中，3审核不通过
        String reqStatus = dynamicRequest.getStatus().toString();
        String status = dynamic.getStatus().toString();
        if ((reqStatus.equals("1") && !status.equals("2")) ||
                (reqStatus.equals("3") && !status.equals("2"))
        ) {
            throw new ApiException("状态异常！");
        }
        dynamic.setStatus(dynamicRequest.getStatus());
        dynamic.setCategoryId(dynamicRequest.getCategoryId());
        dynamic.setReason(dynamicRequest.getReason());
        if (dynamicRequest.getStatus().toString().equals("1") && ActivityEnums.ZERO_EVALUATION.name().equals(dynamic.getActivityType())) {
            dynamic.setIsReason((byte) 1);
            try {
                //测评返本金
                BigDecimal capital = doCounponMoneyByZeroCapital(dynamic.getOrderInfoId());

                log.info("===测评审核通过返本金==={}，{}，", dynamic.getUserId(), capital);
                backZeroEvaluationCapitalMoney(dynamic.getUserId(), CounponMoneyEnum.RELEASE_EVALUATION, capital);
            }catch (Exception e){
                log.error("===测评审核通过返本金失败==={}", e);
            }

        } else if (dynamicRequest.getStatus().toString().equals("3")) {
            dynamic.setIsReason((byte) 0);
        }
        //把该用户改成达人
        if (dynamicRequest.getStatus() == 1){
            userDao.updateIsQuality(dynamic.getUserId());
        }
        dynamicMapper.updateByPrimaryKeySelective(dynamic);


        if (dynamic.getStatus() == 1) {
            DynamicDto dynamicDto = new DynamicDto();
            BeanUtils.copyProperties(dynamic, dynamicDto);
            try {
//                rabbitTemplate.convertAndSend(QueueConstants.DYNAMIC_CHECK_PASS, JSONObject.toJSONString(dynamicDto));
            } catch (Exception e){}
        }
        try {
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(dynamic.getOrderInfoId());
            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
            String orderSource = orders.getOrderSource();
            Integer userId = dynamic.getUserId();
            UsersResponse usersResponse = usersClient.getUsers(userId);
            //发送审核成功短信
            SmsDto smsDto = new SmsDto();
            smsDto.setPhone(usersResponse.getTel());
            smsDto.setCode(usersResponse.getNickname());
            if (!StringUtils.isEmpty(orderSource)) {
                if ("android".equalsIgnoreCase(orderSource) || "ios".equalsIgnoreCase(orderSource) || "APP".equalsIgnoreCase(orderSource) || "JSAPI".equals(orderSource)) {
                    if (dynamic.getStatus() == 1) {
                        smsDto.setType(3);
                    }else {
                        if (ActivityEnums.ZERO_EVALUATION.name().equalsIgnoreCase(ordersInfo.getActivityType())) {
                            //0元试用订单
                            smsDto.setType(4);
                            BigDecimal backAmount = null == orders.getRealTotalMoney() ? BigDecimal.ZERO : orders.getRealTotalMoney()
                                    .add(null == orders.getDeductionMoney() ? BigDecimal.ZERO : orders.getDeductionMoney());
                            smsDto.setCode(dynamicRequest.getReason() + "," + backAmount.toString());
                        }else {
                            //其它订单
                            smsDto.setType(5);
                            smsDto.setCode(dynamicRequest.getReason() + "," + giveBrokerageByDynamic(orders).toString());
                        }
                    }
                }
            }
            if ("true".equals(dynamicSendMsgFlag)) {
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, smsDto);
            }
        } catch (Exception e) {
            log.error("发送审批通过短信");
        }

        if (reqStatus.equals("1")) {
            evaluationProductDao.updateEvaluationStatus(dynamic.getUserId(), dynamic.getProductId());
            evaluationProductDao.updateFallow(dynamic.getId(), 3);
        }
        if (reqStatus.equals("3")) {
            evaluationProductDao.updateFallow(dynamic.getId(), 4);
        }
        updateEvaluationFlowStatus(dynamic.getId(), Integer.parseInt(dynamicRequest.getStatus().toString()));
    }

    /**
     * 赠送测评佣金
     * @param orders
     */
    private BigDecimal giveBrokerageByDynamic(Orders orders) {
        if (null == orders) {
            return BigDecimal.ZERO;
        }
        Integer dynamicId = orders.getDynamicId();
        if (null == dynamicId) {
            return BigDecimal.ZERO;
        }
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicId);
        if (dynamic == null) {
            return BigDecimal.ZERO;
        }
        if (null == dynamic.getIsReason()) {
            dynamic.setIsReason((byte)1);
        }
        if (0 == dynamic.getIsReason() || 1 != dynamic.getStatus()) {
            return BigDecimal.ZERO;
        }
        if (ActivityEnums.ZERO_EVALUATION.name().equals(dynamic.getActivityType())) {
            return BigDecimal.ZERO;
        }
        BigDecimal productPrice = dynamic.getProdcutPrice();//商品售价
        BigDecimal brokerage = productPrice.multiply(new BigDecimal(brokerageRatio)).setScale(4, RoundingMode.HALF_UP).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
        return brokerage;
    }

    private String backZeroEvaluationCapitalMoney(Integer userId, CounponMoneyEnum type, BigDecimal money) {
        BigDecimal addMoney = null == money ? BigDecimal.ZERO : money;
        log.info("===addMoney==={},{}", userId, addMoney);
        UserBalanceDto userBalanceDto = new UserBalanceDto();
        userBalanceDto.setUserId(userId);
        userBalanceDto.setUpdateMoney(addMoney);
        userBalanceDto.setType("ADD");
        userBalanceDto.setSource(type.toString());
        userBalanceDto.setAmountType(1);
        usersClient.updateMoney(userBalanceDto);
        return addMoney.toString();
    }

    private BigDecimal doCounponMoneyByZeroCapital(Integer orderInfoId) {
        //1.查询支付信息
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
        Integer orderId = ordersInfo.getOrderId();
        Orders orders = ordersMapper.selectById(orderId);
        String orderNo = orders.getOrderNo();
        OrdersPayExample ordersPayExample = new OrdersPayExample();
        ordersPayExample.createCriteria().andOrderNoEqualTo(orderNo).andPayTypeEqualTo((byte)2);
        List<OrdersPay> ordersPay = ordersPayMapper.selectByExample(ordersPayExample);
        if (CollectionUtils.isEmpty(ordersPay)) {
            return BigDecimal.ZERO;
        }
        return ordersPay.get(0).getAmount();
    }

    private void updateEvaluationFlowStatus(Integer dynamicId, Integer status) {
        if (status.equals(3)) {
            status = 4;
        }else if (status.equals(1)){
            status = 3;
        }
        int result = evaluationFlowMapper.updateStatusByDynamicId(dynamicId, status);
        if (result <= 0) {
            log.info("===审核动态时更新yx_evaluation_flow失败==={},{}", dynamicId, status);
        }
    }

    @Override
    public void dynamicRecommend(DynamicRequest dynamicRequest) {
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicRequest.getId());
        dynamic.setStatus(dynamicRequest.getStatus());
        dynamicMapper.updateByPrimaryKeySelective(dynamic);
    }

    @Override
    public DynamicResponse positionDynamic(Integer id) {
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(id);
        List<DynamicTopicResponse> relationsByDynamicId = dynamicAndTopicDao.getByDynamicId(dynamic.getId());
        List<DynamicTopic> dynamicTopic = new ArrayList<>();
        relationsByDynamicId.stream().forEach(e->{
            DynamicTopic dynamicTopic1 = new DynamicTopic();
            BeanUtils.copyProperties(e,dynamicTopic1);
            dynamicTopic.add(dynamicTopic1);
        });
        DynamicResponse dynamicResponse = new DynamicResponse();
        BeanUtils.copyProperties(dynamic, dynamicResponse);
        Users users = usersMapper.selectByPrimaryKey(dynamic.getUserId());
        if (users != null) {
            dynamicResponse.setNickName(users.getNickname());
            dynamicResponse.setTel(users.getTel());
        }
        dynamicResponse.setDynamicTopics(dynamicTopic);
        dynamicResponse.setSortAtTopic(relationsByDynamicId.size() == 0 ? null : relationsByDynamicId.get(0).getSortAtTopic());
        return dynamicResponse;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editDynamic(DynamicRequest dynamicRequest) {
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicRequest.getId());
        if (dynamic.getIsZombie() == 1) {
            Users users = usersMapper.selectByPrimaryKey(dynamic.getUserId());
            if(users != null) {
                users.setNickname(dynamicRequest.getNickName());
                usersMapper.updateByPrimaryKeySelective(users);
            }
        }
        OrdersInfo ordersInfo = null;
        if (dynamicRequest.getOrderInfoId() != null) {
            ordersInfo = ordersInfoMapper.selectByPrimaryKey(dynamicRequest.getOrderInfoId());
            Optional.ofNullable(ordersInfo)
                    .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ORDER_NON_EXISTENT)));
        }

        dynamic.setTitle(dynamicRequest.getTitle());
        dynamic.setContent(dynamicRequest.getContent());
        dynamic.setPraiseNum(dynamicRequest.getPraiseNum());
        dynamic.setActivityType(dynamicRequest.getActivityType());
        dynamic.setCommentNum(dynamicRequest.getCommentNum());
        dynamic.setImg(dynamicRequest.getImg());
        dynamic.setIsReason(dynamicRequest.getIsReason());
        dynamic.setContent(dynamicRequest.getContent());
        dynamic.setIsZombie(dynamicRequest.getIsZombie());
        if (ordersInfo != null) {
            dynamic.setOrderInfoId(ordersInfo.getId());
        }
        dynamic.setProdcutPrice(dynamicRequest.getProdcutPrice());
        dynamic.setShareNum(dynamicRequest.getShareNum());
        dynamic.setVideo(dynamicRequest.getVideo());
        dynamic.setStatus(dynamicRequest.getStatus());
        dynamic.setProductImg(dynamicRequest.getProductImg());
        dynamic.setProdcutPrice(dynamicRequest.getProdcutPrice());
        dynamic.setProductName(dynamicRequest.getProductName());
        dynamic.setUpdateTime(new Date());
        dynamic.setDynamicType(dynamicRequest.getDynamicType());
        dynamic.setDynamicText(dynamicRequest.getDynamicText());
        dynamic.setSort(dynamicRequest.getSort());
        dynamic.setUserId(dynamicRequest.getUserId());
        dynamic.setPlatformData(dynamicRequest.getPlatformData());
        dynamic.setIsHome(dynamicRequest.getIsHome());
        dynamic.setCategoryId(dynamicRequest.getCategoryId());
        // 动态管理修改商品id后同步商品信息
        Product product = productMapper.selectByPrimaryKey(dynamicRequest.getProductId());
        dynamic.setProductId(dynamicRequest.getProductId());
        dynamic.setProductName(product.getProductName());
        dynamic.setProductImg(product.getProductImg());
        dynamic.setProdcutPrice(product.getPrice());
        dynamic.setActivityType(product.getActivityType());
        dynamic.setIsZeroEvaluation(product.getIsZeroProduct());
        dynamic.setProductType(product.getProductType());

        dynamicMapper.updateByPrimaryKeySelective(dynamic);
        //1.修改测评关联话题表数据
        //1.1删除原来的话题和测评关系
        dynamicAndTopicService.delByDynamicId(dynamicRequest.getId());
        //1.2重新绑定关系
        List<Integer> integers = dynamicRequest.getDynamicTopics().stream().map(e->e.getId()).collect(Collectors.toList());
        dynamicAndTopicService.createDynamicTopicRelations(dynamicRequest.getId(),integers,dynamicRequest.getSortAtTopic());
    }

    @Override
    public CommonResult searchDynamic(DynamicRequest dynamicRequest) {
        List<DynamicTopic> topicTilte = dynamicRequest.getDynamicTopics();
        List<DynamicAndTopicResponse> dynamicAndTopicResponses = new ArrayList<>();
        List<DynamicResponse> dynamicList = new ArrayList<>();
        //查询时没有选择话题，则查询所有的测评
        if(CollectionUtils.isEmpty(topicTilte)){
            PageHelper.startPage(dynamicRequest.getPageNum(), dynamicRequest.getPageSize());
            dynamicList = dynamicDao.queryDynamic(dynamicRequest);
        }else{
            //根据话题Ids集合,获得话题和测评的关系
            dynamicAndTopicResponses = dynamicAndTopicDao.getRelations(topicTilte);
            //如果当前查询的话题未绑定任何测评内容
            if(CollectionUtils.isEmpty(dynamicAndTopicResponses))
                dynamicList = new ArrayList<>();
            else{
                dynamicRequest.setDynamicAndTopics(dynamicAndTopicResponses);
                PageHelper.startPage(dynamicRequest.getPageNum(), dynamicRequest.getPageSize());
                dynamicList = dynamicDao.queryDynamic(dynamicRequest);
            }
        }
        //获得符合条件的测评集合
        List<DynamicAndTopicResponse> relationsByDynamics = new ArrayList<>();
        if(dynamicList.size() != 0){
            //根据测评获得测评的所有话题
            relationsByDynamics = dynamicAndTopicDao.getRelationsByDynamics(dynamicList);
        }
        CommonPage result = new CommonPage();
        PageInfo<DynamicResponse> pageInfo = new PageInfo<DynamicResponse>(dynamicList);
        result.setTotalPage(pageInfo.getPages());
        result.setPageNum(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());
        CommonResult<DynamicResponse> page = CommonResult.page(dynamicList);
        Optional.ofNullable(dynamicList).orElse(new ArrayList<>());
        List<DynamicAndTopicResponse> finalRelationsByDynamics = relationsByDynamics;
        dynamicList = dynamicList.stream()
                .map(item -> {
                    //添加话题字段值
                    for (DynamicAndTopicResponse finalRelationsByDynamic : finalRelationsByDynamics) {
                        if(item.getId().equals(finalRelationsByDynamic.getDynamicId())){
                            //设置话题属性的值
                            item.setTopicTitles(finalRelationsByDynamic.getTopicTitles());
                            //设置测评内容在话题中的排序值
                            item.setSortAtTopic(finalRelationsByDynamic.getSort());
                        }
                    }
                    List<String> specialList = dynamicSpecialDao.getSpecialList(item.getId());
                    // 根据子订单id查询父订单号
                    if (item.getOrderInfoId() != null) {
                        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(item.getOrderInfoId());
                        if (null != ordersInfo){
                            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
                            if (null != orders){
                                item.setOrderNo(orders.getOrderNo());
                            }
                        }
                    }
                    item.setSpecialList(Optional.ofNullable(specialList)
                            .orElse(new ArrayList<>()));
                    return item;
                }).collect(Collectors.toList());

        result.setList(dynamicList);
        return CommonResult.success(result);
    }

    @Override
    public void deleteDynamic(Integer id) {
        dynamicMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<DynamicsProductResp> selectProductByUserId(Integer userId) {
        DynamicExample dynamicExample = new DynamicExample();
        dynamicExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo((byte) 1);
        List<Dynamic> dynamics = dynamicMapper.selectByExample(dynamicExample);
        List<Integer> productIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dynamics)){
            dynamics.stream().filter(item ->null != item.getProductId()).forEach(item ->{
                productIdList.add(item.getProductId());
            });
        }
        if (CollectionUtils.isEmpty(productIdList)){
            return new ArrayList<>();
        }
        return productDao.selectByIds(productIdList);
    }

    @Override
    public int addOrEditComment(DynamicComment dynamicComment) {
        int count = 0;
        Users users = usersMapper.selectByPrimaryKey(dynamicComment.getUserId());
        if (users == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.USER_NOT_EXIST));
        }
        //新增
        if(dynamicComment.getId() == null || dynamicComment.getId() == 0){
            if(dynamicComment.getCreateTime() == null){
                dynamicComment.setCreateTime(new Date());
            }
            count = dynamicCommentMapper.insertSelective(dynamicComment);
        }else{//修改
            count = dynamicCommentMapper.updateByPrimaryKeySelective(dynamicComment);
        }
        return count;
    }

    @Override
    public int addOrEditReply(DynamicCommentReply dynamicCommentReply) {
        int count = 0;
        Users users = usersMapper.selectByPrimaryKey(dynamicCommentReply.getUserId());
        if (users == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.USER_NOT_EXIST));
        }
        //新增
        if(dynamicCommentReply.getId() == null || dynamicCommentReply.getId() == 0){
            if(dynamicCommentReply.getCreateTime() == null){
                dynamicCommentReply.setCreateTime(new Date());
            }
            count =  dynamicCommentReplyMapper.insertSelective(dynamicCommentReply);
        }else{//修改
            count = dynamicCommentReplyMapper.updateByPrimaryKeySelective(dynamicCommentReply);
        }
        return count;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delCommentOrReply(Integer id, Integer type,String reason) {
        if(type.equals(0)){//评论
            //删除评论
            DynamicComment dynamicComment = new DynamicComment();
            dynamicComment.setId(id);
            dynamicComment.setIsDeleted(1);
            dynamicComment.setDelReason(reason);
            dynamicCommentMapper.updateByPrimaryKeySelective(dynamicComment);

            //删除评论下的回复
            DynamicCommentReply dynamicCommentReply = new DynamicCommentReply();
            dynamicCommentReply.setCommentId(id);
            dynamicCommentReply.setIsDeleted(1);
            dynamicCommentReply.setDelReason("您回复的评论已被删除");
            dynamicCommentReplyMapper.updateByPrimaryKeySelective(dynamicCommentReply);
            return 1;
        }else if(type.equals(1)){//回复
            //删除回复
            DynamicCommentReply dynamicCommentReply = new DynamicCommentReply();
            dynamicCommentReply.setId(id);
            dynamicCommentReply.setIsDeleted(1);
            dynamicCommentReply.setDelReason(reason);
            return dynamicCommentReplyMapper.updateByPrimaryKeySelective(dynamicCommentReply);
        }
        return 0;
    }

    @Override
    public int showOrHide(Integer id,Integer type, Integer isShow) {
        if(type.equals(0)){//评论
            //隐藏或显示评论
            DynamicComment dynamicComment = new DynamicComment();
            dynamicComment.setId(id);
            dynamicComment.setIsShow(isShow);
            dynamicCommentMapper.updateByPrimaryKeySelective(dynamicComment);

            //隐藏或显示评论下的回复
            DynamicCommentReply dynamicCommentReply = new DynamicCommentReply();
            dynamicCommentReply.setCommentId(id);
            dynamicCommentReply.setIsShow(isShow);
            dynamicCommentReplyMapper.updateByPrimaryKeySelective(dynamicCommentReply);
            return 1;
        }else if(type.equals(1)){//回复
            //隐藏回复
            DynamicCommentReply dynamicCommentReply = new DynamicCommentReply();
            dynamicCommentReply.setId(id);
            dynamicCommentReply.setIsShow(isShow);
            return dynamicCommentReplyMapper.updateByPrimaryKeySelective(dynamicCommentReply);
        }
        return 0;
    }

    @Override
    public CommonPage<DynamicCommentReponse> getComments(DynamicCommentRequest dynamicCommentRequest) {
        PageHelper.startPage(dynamicCommentRequest.getPageNum(),dynamicCommentRequest.getPageSize());
        List<DynamicCommentReponse> dynamicCommentReponses =  dynamicCommentDao.getCommentList(dynamicCommentRequest);
        DynamicCommentReplyRequest dynamicCommentReplyRequest = new DynamicCommentReplyRequest();
        dynamicCommentReplyRequest.setPageNum(1);
        //默认取一条回复
        dynamicCommentReplyRequest.setPageSize(1);
        dynamicCommentReplyRequest.setDynamicId(dynamicCommentRequest.getDynamicId());
        dynamicCommentReponses.stream().forEach(e->{
            //1.1获得该评论下的回复
            dynamicCommentReplyRequest.setCommentId(e.getId());
            CommonPage<DynamicCommentReplyResponse> dynamicCommentReplys = getReplyByComment(dynamicCommentReplyRequest);
            e.setReplyResponses(dynamicCommentReplys.getList());
        });
        return CommonPage.restPage(dynamicCommentReponses);
    }

    @Override
    public CommonPage<DynamicCommentReplyResponse> getReplyByComment(DynamicCommentReplyRequest dynamicCommentReplyRequest) {
        PageHelper.startPage(dynamicCommentReplyRequest.getPageNum(),dynamicCommentReplyRequest.getPageSize());
        List<DynamicCommentReplyResponse> dynamicCommentReplyResponses = dynamicCommentReplyDao.selectByEntity(dynamicCommentReplyRequest);
        return CommonPage.restPage(dynamicCommentReplyResponses);
    }
}
